<?php
/* Finding Nemo : finding missing children campaign banner
   Version 1.0

   Data update                 : sogmi, j.parker
   Server setting and managing : inureyes
   Plugin coding               : inureyes, j.parker
   Last modified at            : 2008.06.11

   License : General Public License
   Visit http://bringbring.com/entry/FootNote for the detail

   General Public License
   http://www.gnu.org/licenses/gpl.html
													     
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
*/ 

function findNemo_initConfigVal( &$data ){
	$postHeaderDefault = '<fieldset>
<legend>미아를 찾습니다</legend>';
	$postFooterDefault = '</fieldset>';
	$sidebarHeaderDefault = '<div>
<h3>미아를 찾습니다</h3>';
	$sidebarFooterDefault = '</div>';
	$data['b1'] = !isset($data['b1'])?true:$data['b1'];
	$data['b2']	= !isset($data['b2'])?true:$data['b2'];
	$data['postListLength']	 = !isset($data['postListLength'])?2:$data['postListLength'];
	$data['sidebarListLength'] = !isset($data['sidebarListLength'])?1:$data['sidebarListLength']; 
	$data['postHeader']	= !isset($data['postHeader'])?$postHeaderDefault:$data['postHeader'];
	$data['postFooter']	= !isset($data['postFooter'])?$postFooterDefault:$data['postFooter'];
	$data['sidebarHeader']	= !isset($data['sidebarHeader'])?$sidebarHeaderDefault:$data['sidebarHeader'];
	$data['sidebarFooter']	= !isset($data['sidebarFooter'])?$sidebarFooterDefault:$data['sidebarFooter'];
	$data['imageSize']	= !isset($data['imageSize'])?50:$data['imageSize'];
	$data['lineColor']	= !isset($data['lineColor'])?'#e3e3e3':$data['lineColor'];
}

function findingNemoBanner($target, $mother) {
	global $suri, $entries, $configVal;
	requireComponent('Tattertools.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	findNemo_initConfigVal($data);
	if ($suri['directive'] != "/rss" && $suri['directive'] != "/sync" && $data['b1'] && (isset($data['b3']) && !$data['b3'])) {
		$target .= '<div id="findingNemoContent'.$mother.'" class="findingNemoEntry"><script type="text/javascript">findingNemo(\''.$mother.'\');</script></div>';
	}
	return $target;
}

function findingNemoBannerTag($target) {
	global $suri, $entries, $configVal;
	requireComponent('Tattertools.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	findNemo_initConfigVal($data);
	if ($suri['directive'] != "/rss" && $suri['directive'] != "/sync" && $data['b1'] && $data['b3']) {
		$target .= '<div id="findingNemoContent[##_article_rep_id_##]" class="findingNemoEntry"><script type="text/javascript">findingNemo(\'[##_article_rep_id_##]\');</script></div>';
	}
	return $target;
}

function SB_findingNemo($parameter) {
	global $suri,  $configVal;
	requireComponent('Tattertools.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	findNemo_initConfigVal($data);	
	if (isset($parameter['preview'])) {
		$retval = "사이드바에 미아찾기 배너를 출력합니다.";
		return $retval;
	}
	if ($data['b2']) {
		$target = '<div id="findingNemoContentSidebar"><script type="text/javascript">findingNemo("Sidebar");</script></div>';
	}
	return $target;
}

function findingNemo_reader($target , $mother) {
	global $service, $configVal;
	requireComponent("Eolin.PHP.Core");
	requireComponent('Tattertools.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	findNemo_initConfigVal($data);		
	$lineColor	= (strpos($data['lineColor'], "#")===0)?$data['lineColor']:"#".$data['lineColor'];

	$_POST["idkey"] = !isset($_POST["idkey"]) ?'Sidebar':$_POST["idkey"];
	$nemoEntries = findingNemo_getXMLResource();
	if (!is_null($nemoEntries) && is_array($nemoEntries) && count($nemoEntries) > 0) {
		$contentWidth =	misc::getContentWidth();
		$target = "<div class=\"findingNemo\">";
		if($_POST["idkey"] == "Sidebar"){
			$target .= $data['sidebarHeader'];
			$listLength = $data['sidebarListLength'];
		}else{
			$target .= $data['postHeader'];
			$listLength = $data['postListLength'];
		}

		$i = 0;
		shuffle($nemoEntries);
		foreach($nemoEntries as $item) {
			preg_match('@\<img(.+)\>@isU', $item['description'], $temp);
			preg_match('/src="([^"]+)"/i', $temp[0], $temp1);
			preg_match('/width="([1-9][0-9]*)"/i', $temp[0], $temp2);
			preg_match('/height="([1-9][0-9]*)"/i', $temp[0], $temp3);
			$tempIMG = '<img src="'.$temp1[1].'" width="'.$data['imageSize'].'" onclick="findingNemoPopup(this.src,\''.rawurldecode($item['title']).'\'); return false;"/>';
			$item['description'] = str_replace(array('<P>','</P>'),array('',''), $item['description']);
			$description = preg_replace('@\<div(.+)\</div>@isU', '<div class="findingNemoItem" title="크게보기"><div style="width:'.$data['imageSize'].'px;height:'.$data['imageSize'].'px;overflow:hidden;">'.$tempIMG.'</div></div>', $item['description']);
			$target .= '<div style="'.(($_POST["idkey"] == "Sidebar")?($i == ($listLength-1)?'':'border-bottom:1px dotted '.$lineColor.';').'margin:4px 0 0 0;padding-bottom:4px;':'float:left;width:'.(($contentWidth/2)-20).'px;margin:5px 0 0 5px;').'">'.$description.'</div>';
			if($i == ($listLength-1)) break;
			else $i++;
		}

		// TNF Needlworks & 어린이재단 링크
		$nwLink = "Supported by <a href=\"http://needlworks.org/projects/findingNemo\" onclick=\"window.open(this.href); return false;\" title=\"Needlworks / Tatter Network Foundation\">Needlworks</a>";
		$msLink = "<a href=\"http://www.missingchild.or.kr\" onclick=\"window.open(this.href); return false;\" title=\"실종아동전문기관\">어린이재단</a>";
		if($_POST["idkey"] == "Sidebar"){
			$target .= "<div class=\"findingNemoInfoS\"><div class=\"findingNemoIn\">{$nwLink}<br />{$msLink}</div></div>";
			$target .= $data['sidebarFooter'];
		}else{
			$target .= "<div style=\"clear:both;border-bottom:1px dotted {$lineColor};padding-top:5px;\"></div>";
			$target .= "<div class=\"findingNemoInfoE\"><div class=\"findingNemoIn\">{$nwLink}, {$msLink}</div></div>";
			$target .= $data['postFooter'];
		}
		$target .= "</div>";
	} else {
		$target .= _t('<p>미아 정보가 없거나 가져올 수 없습니다.</p>');
	}
	unset($nemoEntries);

	header('Content-Type: text/xml; charset=UTF-8');
	echo '<?xml version="1.0" encoding="utf-8"?><response><error>0</error><findingNemoBlock><![CDATA['.$target.']]></findingNemoBlock></response>';
}
function findingNemo_getAlterUrl($link,$urlInfo){
	requireComponent('Tattertools.Function.misc');
	$attributes = misc::getAttributesFromString($link);
	if(!isset($attributes['href'])) return false;
	$rssInfo = parse_url($attributes['href']);
	$rssURL = false;
	if(isset($rssInfo['scheme']) && $rssInfo['scheme'] == 'http')
		$rssURL = $attributes['href'];
	else if(isset($rssInfo['path'])) {
		if($rssInfo['path']{0} == '/')
			$rssURL = "{$urlInfo['scheme']}://{$urlInfo['host']}{$rssInfo['path']}";							
		else
			$rssURL = "{$urlInfo['scheme']}://{$urlInfo['host']}".(isset($urlInfo['path']) ? rtrim($urlInfo['path'], '/') : '').'/'.$rssInfo['path'];
	}
	return $rssURL;
}

function findingNemo_getRemoteXml($url){
	requireComponent('Eolin.PHP.HTTPRequest');
	$request = new HTTPRequest($url);
	$request->timeout = 3;
	if (!$request->send())
		return null;
	$xml = $request->responseText;
	unset($request);
	return $xml;
}

function findingNemo_getXMLResource($url=null) {
	global $service;
	$nemoEntries = null;
	$url = is_null($url)?'http://resource.tattersite.com/findingNemo/rss':$url;	
	if(defined('__TISTORY__') ){
		$NemoCacheId = 'findingNemo_NemoCache';
		$cacheOwner = -1;
		requireComponent('Eolin.PHP.PageCache');
		$cache = new DataCache($NemoCacheId, $cacheOwner);
		if ($cache->exist()) {
			$cache->getData($nemoEntries);
			unset($cache);
		}
		unset($cache);
		return $nemoEntries;
	}
	$xml = findingNemo_getRemoteXml($url);
	if(is_null($xml)) return $nemoEntries;
	$xml = base64_decode($xml);
	$xmls = new XMLStruct();
	if (!$xmls->open($xml, $service['encoding'])) {
		if(preg_match_all('/<link .*?rel\s*=\s*[\'"]?alternate.*?>/i', $xml, $matches)) {
			$urlInfo = parse_url($url);
			foreach($matches[0] as $link) {
				$rssURL = findingNemo_getAlterUrl($link,$urlInfo);
				if($rssURL && $url != $rssURL)
					return findingNemo_getXMLResource($rssURL);
			}
		}
	}else if ($xmls->getAttribute('/rss', 'version')) {
		$nemoEntries = array();
		for ($i = 0; $link = $xmls->getValue("/rss/channel/item[$i]/link"); $i++) {
			$item = array('permalink' => rawurldecode($link));
			$item['title'] = $xmls->getValue("/rss/channel/item[$i]/title");
			$item['description'] = $xmls->getValue("/rss/channel/item[$i]/description");
			$item['nemoNumber'] = $xmls->getValue("/rss/channel/item[$i]/category");
			array_push($nemoEntries, $item);
		}
	}
	return $nemoEntries;
}

function findingNemoScript($target) {
	global $blogURL;
	$styleScript  = "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$blogURL."/plugin/findingNemoScriptStyle/?mode=style\" />".CRLF;
	$styleScript .= "<script type=\"text/javascript\" src=\"".$blogURL."/plugin/findingNemoScriptStyle/?mode=script\"></script>".CRLF;
	$target .= $styleScript;
	return $target;
}

function findingNemoScriptStyle($target){
	global $blogURL, $pluginURL, $configVal;
	requireComponent('Tattertools.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	findNemo_initConfigVal($data);
	$lineColor = (strpos($data['lineColor'], "#")===0)?$data['lineColor']:"#".$data['lineColor'];
	if($_GET['mode'] == "style"){
		header('Content-type: text/css; charset=utf-8');
		echo '
			/* finding Nemo CSS Setting */
			#findingNemoContentSidebar div {margin-top:0;}
			.findingNemo		{ margin:0px;font:8.5pt dotum, AppleGothic;}
			.findingNemo fieldset{ margin:0px; border:1px solid '.$lineColor.'; padding:0px;}

			.findingNemo legend { font-weight:bold; margin:0 0 0 5px;}
			*html .findingNemo legend { margin:0; padding:0 !important;}
			*:first-child+html .findingNemo legend { margin:0; padding:0 !important;}
			
			.findingNemo h3 { font-weight:bold; padding:0px !important;}
			.findingNemoEntry	{ margin-top:20px;}
			.findingNemoItem	{ float:left;border:1px solid '.$lineColor.';padding:2px; margin:0px 5px 0px 0px; cursor:pointer;}
			.findingNemoInfoS	{ margin:5px 0 8px 0; border:3px solid '.$lineColor.'; text-align:right;padding:5px 4px 3px 0;}
			.findingNemoInfoE	{ margin:7px 4px 5px 0; text-align:right;} 
		';
	}else if($_GET['mode'] == "script"){
		header('Content-type: text/javascript; charset=utf-8');
		echo '
			function findingNemo(id) {
				var request = new HTTPRequest("POST", "'.$blogURL.'/plugin/finding/");
				var	obj = document.getElementById("findingNemoContent" + id);
				request.onSuccess = function() {
					try {
						if (obj != null) obj.innerHTML = this.getText("/response/findingNemoBlock");
					} catch(e) { }
				}
				request.send("idkey="+id);
			}
			
			function findingNemoPopup(url, name) {
				try {
					var left = Math.floor((screen.availWidth - 250) / 2);
					var top = Math.floor((screen.availHeight - 100) / 2);
					try { findingNemoImagePopup.close(); } catch(e) { }
					findingNemoImagePopup = window.open("", "", "width=250, height=100, left=" + left + ", top=" + top + ", scrollbars=no, resizable=yes");
					findingNemoImagePopup.document.open("text/html", "replace");
					findingNemoImagePopup.document.write(
						\'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\r\n\' +
						\'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko">\r\n\' +
						\'	<head>\r\n\' +
						\'		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>\r\n\' +
						\'		<title>\' + name + \' 어린이 </title>\r\n\' +
						\'		<style type="text/css">\r\n\' +
						\'			html, body { width: 100%; height: 100%; margin: 0; padding: 0; cursor: pointer; text-align: center; line-height: 0; }\r\n\' +
						\'			#Container { width: 100%; height: 100%; overflow: auto; }\r\n\' +
						\'			#NemoImage { text-align: center; }\r\n\' +
						\'			#BottomInfo {line-height:130%; padding:4px 0 2px 0;border-top:1px solid #ffffff;background-color:#40707B;color:#ffffff;text-align:center;font-size:9pt; }\r\n\' +
						\'		</style>\r\n\' +
						\'		<script type="text/javascript">\r\n\' +
						((navigator.userAgent.indexOf("Safari") > -1) ?
						\'			function resizeImage() {\r\n\' :
						\'				window.onload = function() {\r\n\') +
						\'				var container = document.getElementById("Container");\r\n\' +
						\'				var image = document.getElementById("Image");\r\n\' +
						\'				var resizeWidth = 0, resizeHeight = 0, positionTop = 0, positionLeft = 0;\r\n\' +
						\'				var offsetTop = window.screenTop || window.screenY;\r\n\' +
						\'				var offsetLeft = window.screenLeft || window.screenX;\r\n\' +
						\'				if(navigator.userAgent.indexOf("Safari") > -1) {\r\n\' +
						\'					var width = Math.min(image.width + 50, screen.availWidth - 100);\r\n\' +
						\'					var height = Math.min(image.height + 50, screen.availHeight - 100);\r\n\' +
						\'					window.moveTo((screen.availWidth - width) / 2, (screen.availHeight - height) / 2);\r\n\' +
						\'					window.resizeTo(width, height);\r\n\' +
						\'					return;\r\n\' +
						\'				}\r\n\' +
						\'				if(container.scrollWidth > container.offsetWidth) {\r\n\' +
						\'					resizeWidth += container.scrollWidth - container.offsetWidth;\r\n\' +
						\'					if(container.offsetWidth + resizeWidth + 100 > screen.availWidth) {\r\n\' +
						\'						resizeWidth = screen.availWidth - container.offsetWidth - 100;\r\n\' +
						\'						positionLeft = -resizeWidth / 2;\r\n\' +
						\'						resizeHeight += 20;\r\n\' +
						\'					}\r\n\' +
						\'					else {\r\n\' +
						\'						positionLeft = -resizeWidth / 2;\r\n\' +
						\'					}\r\n\' +
						\'				}\r\n\' +
						\'				if(container.scrollHeight > container.offsetHeight) {\r\n\' +
						\'					resizeHeight += container.scrollHeight - container.offsetHeight;\r\n\' +
						\'					if(container.offsetHeight + resizeHeight + 100 > screen.availHeight - 50) {\r\n\' +
						\'						resizeHeight = screen.availHeight - container.offsetHeight - 100 - 40;\r\n\' +
						\'						positionTop = -resizeHeight / 2;\r\n\' +
						\'						resizeWidth += 20;\r\n\' +
						\'					}\r\n\' +
						\'					else {\r\n\' +
						\'						positionTop = -resizeHeight / 2;\r\n\' +
						\'					}\r\n\' +
						\'				}\r\n\' +
						\'				if(resizeWidth == 0 && resizeHeight == 0)\r\n\' +
						\'					image.style.marginTop = ((container.offsetHeight - image.height) / 2) + "px";\r\n\' +
						\'				window.moveBy(positionLeft, positionTop - 35);\r\n\' +
						\'				window.resizeBy(resizeWidth, resizeHeight);\r\n\' +
						\'			}\r\n\' +
						\'		</script>\r\n\' +
						\'	</head>\r\n\' +
						\'	<body onclick="window.close();">\r\n\' +
						\'		<div id="Container" title="\' + name + \' 실종 어린이">\' +
						((navigator.userAgent.indexOf("Safari") > -1) ?
						\'			<div id="NemoImage"><img id="Image" src="\' + url + \'" alt="\' + name + \' 어린이" onload="resizeImage()"/></div>\' :
						\'			<div id="NemoImage"><img id="Image" src="\' + url + \'" alt="\' + name + \' 어린이"/></div>\') +
						\'			<div id="BottomInfo">제보전화 : 02) 777-0182</div>\' +
						\'		</div>\' +
						\'	</body>\r\n\' +
						\'</html>\'
					);
					findingNemoImagePopup.document.close();
					if(findingNemoImagePopup.document.focus)
						findingNemoImagePopup.document.focus();
				}
				catch(e) {
					window.open(url, "_blank");
				}

			}
		';
	}
	flush();
}

function findingNemo_DataSet($DATA){
	requireComponent('Tattertools.Function.misc');
	$cfg = misc::fetchConfigVal($DATA);
	return true;
}
?>
